package be.kuleuven.peno3.mobiletoledo.view;
import java.util.Calendar;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import be.kuleuven.peno3.mobiletoledo.R;
import be.kuleuven.peno3.mobiletoledo.Data.Client.ScheduleClient;
import be.kuleuven.peno3.mobiletoledo.model.CourseActivity;
import be.kuleuven.peno3.mobiletoledo.model.POI;
import be.kuleuven.peno3.mobiletoledo.model.Schedule;
import be.kuleuven.peno3.mobiletoledo.model.User;
import be.kuleuven.peno3.mobiletoledo.view.campusmap.CampusMap;

/*
 * Swiping-code komt van http://www.codeshogun.com/blog/2009/04/16/how-to-implement-swipe-action-in-android/
 */
public class ScheduleView extends Activity {
	private static final int SWIPE_MIN_DISTANCE = 120;
	private static final int SWIPE_MAX_OFF_PATH = 250;
	private static final int SWIPE_THRESHOLD_VELOCITY = 200;
	private static final int[] COLORS = new int[] { 0xFF464646, 0xFF272727 };
	
	private int course_id;
	private String group;
	private String study_programme;
	private Calendar currentDay;
	private GestureDetector gestureDetector;
	private View.OnTouchListener gestureListener;
	private LinearLayout ll;
	private ScrollView sv;
	
	private HashMap<String, POI> pois;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setFields();
		Thread t = new Thread(new LocalBackupRunnable());
		t.start();
		
		pois=new HashMap<String, POI>();
		
		gestureDetector = new GestureDetector(new MyGestureDetector());
        gestureListener = new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (gestureDetector.onTouchEvent(event)) {
                    return true;
                }
                return false; 
            }
        };

        sv = new ScrollView(this.getApplicationContext());
        sv.setForegroundGravity(Gravity.TOP);
        sv.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
        ll = new LinearLayout(this.getApplicationContext());
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
        sv.addView(ll);
		setContentView(sv);
		sv.setOnTouchListener(gestureListener);
		displayDay(currentDay);
	}
	
	private void displayDay(Calendar day){
		clearActivities();
		Calendar beginDay = Calendar.getInstance();
		Calendar endDay = Calendar.getInstance();
		beginDay.set(day.get(Calendar.YEAR),day.get(Calendar.MONTH),day.get(Calendar.DAY_OF_MONTH),0,0,0);
		endDay.set(day.get(Calendar.YEAR),day.get(Calendar.MONTH),day.get(Calendar.DAY_OF_MONTH),23,59,59);
		Schedule schedule = ScheduleClient.getSchedule(beginDay,endDay,course_id,group,study_programme,this.getApplicationContext());
		CourseActivity[] dayActivities = schedule.getActivities();
		TextView bar = new TextView(this.getApplicationContext());
		bar.setText("Lessenrooster");
		bar.setTextSize(TypedValue.COMPLEX_UNIT_PT, 14);
		bar.setGravity(Gravity.CENTER);
		bar.setBackgroundDrawable(getResources().getDrawable(R.drawable.bar));
		ll.addView(bar);
		addDisplayText(translateDay(day.get(Calendar.DAY_OF_WEEK)) + " " + day.get(Calendar.DAY_OF_MONTH) + "/" + (day.get(Calendar.MONTH)+1),22, Typeface.NORMAL, 0xFF000000, 0xFF69931e, Gravity.CENTER_HORIZONTAL, 0, false, "");
		
		ImageView line = new ImageView(this.getApplicationContext());
		line.setImageDrawable(getResources().getDrawable(R.drawable.line_full));
		line.setPadding(0, 5, 0, 5);
		ll.addView(line);
		
		if(dayActivities == null){
			addDisplayText("Geen vakken gevonden", 16,Typeface.BOLD,0xFF000000,0xFFEEEEEE,Gravity.CENTER_HORIZONTAL, 180, false, "");
		}
		else{
			for(int i=0; i < dayActivities.length; i++){
				if(dayActivities[i] != null){
					addActivity(dayActivities[i], i);
				}
			}
		}
    }
	private void addDisplayText(String content, float size,int tf ,int bgcolor, int textcolor, int gravity, int padding, boolean click, String tag){
		TextView text = new TextView(this.getApplicationContext());
		text.setText(content);
		text.setBackgroundColor(bgcolor);
		text.setTypeface(Typeface.DEFAULT, tf);
		text.setTextSize(size);
		text.setTextColor(textcolor);
		text.setGravity(gravity);
		text.setTag(tag);
		text.setPadding(0, padding, 0, 0);
		ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
		ll.addView(text,params);
	
		}
	
    private void addActivity(CourseActivity activity, int counter) {
    	String beginTimeHour = activity.getBeginDate().get(Calendar.HOUR_OF_DAY) +":";
    	String beginTimeMinute = "" + activity.getBeginDate().get(Calendar.MINUTE);
    	if(beginTimeMinute.length() == 1){
    		beginTimeMinute = "0" + beginTimeMinute;
    	}
    	String beginTime = beginTimeHour + beginTimeMinute;
    	String endTimeHour = activity.getEndDate().get(Calendar.HOUR_OF_DAY)+":";
    	String endTimeMinute = "" + activity.getEndDate().get(Calendar.MINUTE);
    	if(endTimeMinute.length() == 1){
    		endTimeMinute = "0" + endTimeMinute;
    	}
    	String endTime = endTimeHour + endTimeMinute;
    	String time = beginTime + " - " + endTime;
    	String location = activity.getPoi().getDescription();
    	String course = activity.getCourse().getCourseName();
    	String content = course + "\n" + location;
    	
    	pois.put(content, activity.getPoi());
    	
    	addDisplayText(time, 14, Typeface.BOLD, COLORS[counter%2],0xFFEEEEEE,Gravity.LEFT, 0, true, content);
    	addDisplayText(content,14, Typeface.NORMAL, COLORS[counter%2],0xFFEEEEEE,Gravity.LEFT, 0, true, content);
	}

	public void clearActivities() {
		ll.removeAllViews();
	}
	private String translateDay(int day){
		String[] days = new String [] {"", "Zondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag"};
		return days[day];		
	}
	private void clickedAtLocation(MotionEvent e){
		View v = ll.getChildAt(0);
		for(int i=3; i < ll.getChildCount(); i++){
			v = ll.getChildAt(i);
			//checks if the click was inside this child view
			if((e.getY() >= v.getTop()) && (e.getY() <= v.getBottom())){
				//Launches the CampusMap
				Intent intent = new Intent(this, CampusMap.class);
				POI poi=pois.get(((TextView) v).getTag().toString());
				if(poi != null){
					intent.putExtra("latitude", poi.getLocation().getLatitude());
					intent.putExtra("longitude", poi.getLocation().getLongitude());
					intent.putExtra("name", poi.getName());
					intent.putExtra("description", poi.getDescription());
					startActivity(intent);
				}
				else {
					Toast.makeText(this.getApplicationContext(), "Er zijn geen locatiegegevens beschikbaar voor deze les.", Toast.LENGTH_SHORT).show();
					return;
				}
			}
		}
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (gestureDetector.onTouchEvent(event))
			return true;
		else
			return false;
	}
	
	private class MyGestureDetector extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                    return false;
                // right to left swipe
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                	Calendar nextDay = Calendar.getInstance();   
                	nextDay.setTimeInMillis(currentDay.getTimeInMillis()+86400000);
                	currentDay = nextDay;
                	displayDay(currentDay);   
                }  
                else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                	Calendar previousDay = Calendar.getInstance();
                	previousDay.setTimeInMillis(currentDay.getTimeInMillis()-86400000);
                	currentDay = previousDay;
                	displayDay(currentDay);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }
        @Override
        public boolean onSingleTapConfirmed(MotionEvent e){
        	System.out.println("Single TAP at " + e.getX() + ","+e.getY());
        	clickedAtLocation(e);
        	return false;
        }
	}
	
	private void setFields (){
		currentDay = Calendar.getInstance();
		try {
			course_id = this.getIntent().getExtras().getInt("course_id");
		} catch(NullPointerException e) {
			course_id = 0;
		}
		try {
			group = User.getInstance().getGroup();
			study_programme = User.getInstance().getStudyprogramme();
		}
		catch (NullPointerException e){
			e.printStackTrace(); 
		}
	}
	
	private class LocalBackupRunnable implements Runnable {
		@Override
		public void run() {
			int i=0;
			Calendar begin = Calendar.getInstance();
			begin.set(Calendar.HOUR_OF_DAY, 0);
			begin.set(Calendar.MINUTE, 0);
			begin.set(Calendar.SECOND, 0);

			Calendar end=Calendar.getInstance();
			end.set(Calendar.HOUR_OF_DAY, 23);
			end.set(Calendar.MINUTE, 59);
			end.set(Calendar.SECOND, 59);
			

			while (i<14){
				ScheduleClient.getSchedule(begin, end, 0, group,study_programme, ScheduleView.this.getApplicationContext());
				begin.set(Calendar.DAY_OF_MONTH, begin.get(Calendar.DAY_OF_MONTH)+1);
				end.set(Calendar.DAY_OF_MONTH, end.get(Calendar.DAY_OF_MONTH)+1);
				
				i++;
			}
		}
	}
}
